﻿using System.Net;
using System.Net.Security;
using System.Text.Json;

namespace IoTApp
{
    public partial class MainPage : ContentPage
    {
        private const string _host = "https://foreign-trade.devonline.cn";
        private static readonly Color _colorOn = Color.FromRgba(81, 43, 212, 255);
        private static readonly Color _colorOff = Color.FromRgba(81, 43, 212, 50);
        private static readonly Dictionary<int, bool> _lights = [];
        public MainPage()
        {
            InitializeComponent();
            _lights.Clear();
            BtnLightBedRoom.IsEnabled = false;
            BtnLightLivingRoom.IsEnabled = false;
            SwitchButtonStyle(BtnLightBedRoom, false);
            SwitchButtonStyle(BtnLightLivingRoom, false);

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, cert, chain, errors) => true);
        }

        /// <summary>
        /// 查看灯的状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnGetLightsStateClicked(object sender, EventArgs e)
        {
            await GetLightsStateAsync();
        }

        /// <summary>
        /// 开关卧室灯
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnLightBedRoomClicked(object sender, EventArgs e)
        {
            var on = !_lights[1];
            SwitchButtonStyle(BtnLightBedRoom, on);
            using var httpClient = new HttpClient();
            await httpClient.GetAsync($"{_host}/api/Devices/Switch/{1}/{on}");
            _lights[1] = on;
        }

        /// <summary>
        /// 开关客厅灯
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnLightLivingRoomClicked(object sender, EventArgs e)
        {
            var on = !_lights[2];
            SwitchButtonStyle(BtnLightLivingRoom, on);
            using var httpClient = new HttpClient();
            await httpClient.GetAsync($"{_host}/api/Devices/Switch/{2}/{on}");
            _lights[2] = on;
        }

        /// <summary>
        /// 获取当前灯的状态
        /// </summary>
        /// <returns></returns>
        private async Task GetLightsStateAsync()
        {
            var json = string.Empty;
            var lights = new Dictionary<int, bool>();

            try
            {
                using var httpClient = new HttpClient();
                json = await httpClient.GetStringAsync($"{_host}/api/Devices/Lights");
                lights = JsonSerializer.Deserialize<Dictionary<int, bool>>(json) ?? new Dictionary<int, bool>
                {
                    { 1, false },
                    { 2, false }
                }; ;
            }
            catch (Exception)
            {
                lights = new Dictionary<int, bool>
                {
                    { 1, false },
                    { 2, false }
                };
            }

            foreach (var light in lights)
            {
                if (!_lights.TryAdd(light.Key, light.Value))
                {
                    _lights[light.Key] = light.Value;
                }

                if (light.Key == 1)
                {
                    BtnLightBedRoom.IsEnabled = true;
                    SwitchButtonStyle(BtnLightBedRoom, light.Value);
                }
                else if (light.Key == 2)
                {
                    BtnLightLivingRoom.IsEnabled = true;
                    SwitchButtonStyle(BtnLightLivingRoom, light.Value);
                }
            }
        }

        /// <summary>
        /// 切换按钮颜色
        /// </summary>
        /// <param name="button"></param>
        /// <param name="on"></param>
        private static void SwitchButtonStyle(Button button, bool on)
        {
            button.BackgroundColor = on ? _colorOn : _colorOff;
        }
    }
}
